package com.atguigu.stuty.locks;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author early morning
 * @Create 2025/4/24 15:17
 * @Description: 死锁的实现方式
 */
public class DeadLock {
    public static void main(String[] args) {

        final Lock lockA = new ReentrantLock();
        final Lock lockB = new ReentrantLock();

        // 两个线程
        new Thread(() -> {
            // Runnable 接口的实现类
            lockA.lock();
            try {
                System.out.println(Thread.currentThread().getName()+ "\t" + "线程持有A锁，尝试获取B锁");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                lockB.lock();
                try {
                    System.out.println(Thread.currentThread().getName()+ "\t" + "成功获取B锁");
                } finally {
                    lockB.unlock();
                }
            } finally {
                lockA.unlock();
            }
        },"A").start();
        new Thread(() -> {
            // Runnable 接口的实现类
            lockB.lock();
            try {
                System.out.println(Thread.currentThread().getName()+ "\t" + "线程持有B锁，尝试获取A锁");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                lockA.lock();
                try {
                    System.out.println(Thread.currentThread().getName()+ "\t" + "成功获取B锁");
                } finally {
                    lockA.unlock();
                }
            } finally {
                lockB.unlock();
            }
        },"B").start();
    }
}
